package com.jack.leetcode.每日一题;

import java.util.LinkedList;

public class 字符串解码 {

    public static void main(String[] args) {
        String s = "3[a2[c]]";
        System.out.println(decodeString(s));
        s = "100[leetcode]";
        System.out.println(decodeString(s));
    }

    public static String decodeString(String s) {
        StringBuilder result = new StringBuilder();
        int multi = 0;
        LinkedList<Integer> stack_multi = new LinkedList<>();
        LinkedList<String> stack_res = new LinkedList<>();
        for (Character c : s.toCharArray()) {
            if (c.equals('[')) {
                stack_multi.add(multi);
                stack_res.add(result.toString());
                multi = 0;
                result = new StringBuilder();
            } else if (c.equals(']')) {
                int last_multi = stack_multi.removeLast();
                StringBuilder tmp = new StringBuilder();
                for (int i = 0; i < last_multi; i++) {
                    tmp.append(result);
                }
                result = new StringBuilder(stack_res.removeLast() + tmp);
            } else if (c >= '0' && c <= '9') {
                multi = multi * 10 + (c - '0');
            } else {
                result.append(c.toString());
            }
        }
        return result.toString();
    }
}
